package com.aoxon.cargo.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.activity.n.PurMapActivity;
import com.aoxon.cargo.adapter.PurGoodsGridAdapter;
import com.aoxon.cargo.adapter.PurStoreGridAdapter;
import com.aoxon.cargo.bean.Cloth;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.bean.Picture;
import com.aoxon.cargo.bean.Supplier;
import com.aoxon.cargo.cache.PurCache;
import com.aoxon.cargo.cache.SupCache;
import com.aoxon.cargo.component.MyLoadCloth;
import com.aoxon.cargo.component.MyRadioButton;
import com.aoxon.cargo.component.SupplierInfoShow;
import com.aoxon.cargo.component.WaterFallShowStore;
import com.aoxon.cargo.component.n.WaterFallGoodsView;
import com.aoxon.cargo.database.DataService;
import com.aoxon.cargo.service.CancleCollectSupplierService;
import com.aoxon.cargo.service.ClickGoodsService;
import com.aoxon.cargo.service.CollectSupplierService;
import com.aoxon.cargo.service.GoodsFromSupplierService;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.shared.CollectSupplierShared;
import com.aoxon.cargo.shared.DialShared;
import com.aoxon.cargo.shared.SupIndexShared;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.EnvironmentUtil;
import com.aoxon.cargo.util.ExecutorUtil;
import com.aoxon.cargo.util.ToastUtil;
import com.google.gson.reflect.TypeToken;

/**
 * 采购端商家详情页面
 * 
 * @author ZZJ
 * 
 */
public class PurSupplierDetailsActivity extends BaseActivity implements
		MyRadioButton.OnCheckedListener {

	private ImageView ivReturnButton;
	private ImageView ivGPSButton;
	private ImageView ivBackButton;
	private ImageView ivPhoneButton;

	private RadioButton rbCollectButton;

	private TextView tvTitle;

	private MyRadioButton myRadioButton;
	private SupplierInfoShow supplierInfoShow;

	private PurGoodsGridAdapter gAdapter;
	private PurStoreGridAdapter sAdapter;
	private WaterFallGoodsView wShowGoods;
	private WaterFallShowStore wShowStore;

	private DataService dataService = new DataService(this);
	private ClickGoodsService clickGoodsService = (ClickGoodsService) MyServiceFactory
			.getInstance(MyServiceFactory.CLICK_GOODS);
	private CollectSupplierService collectSupplierService = (CollectSupplierService) MyServiceFactory
			.getInstance(MyServiceFactory.COLLECT_SUPPLIER);
	private CancleCollectSupplierService cancleCollectSupplierService = (CancleCollectSupplierService) MyServiceFactory
			.getInstance(MyServiceFactory.CANCLE_COLLECT_SUPPLIER);
	private GoodsFromSupplierService goodsFromSupplierService = (GoodsFromSupplierService) MyServiceFactory
			.getInstance(MyServiceFactory.GOODS_FROM_SUPPLIER);

	private List<Cloth> disCloths = new ArrayList<Cloth>(); // 显示商家所有物品的列表
	private List<Supplier> colSuppliers = new ArrayList<Supplier>();
	private List<Picture> disStorePicture = new ArrayList<Picture>();

	private Supplier supplier;
	private Supplier user;
	private String deviceId = null;

	private boolean isShowGoods = true;
	private int collecteNumber = -1;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setup();
	}

	private void setup() {
		user = SupIndexShared.getSupplier();
		try {
			TelephonyManager telMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
			deviceId = telMgr.getDeviceId();
		} catch (Exception e) {
			e.printStackTrace();
		}
		setContentView(R.layout.pur_supplier_details);
		ivReturnButton = (ImageView) findViewById(R.id.ivPublicTitleReturn);
		ivBackButton = (ImageView) findViewById(R.id.ivPurDetailsBack);
		ivPhoneButton = (ImageView) findViewById(R.id.ivPurDetailsPhone);
		rbCollectButton = (RadioButton) findViewById(R.id.rbPurDetailsCollection);

		ivGPSButton = (ImageView) findViewById(R.id.ivPublicTitleOther);
		ivGPSButton.setImageResource(R.drawable.button_gps);
		ivGPSButton.setOnClickListener(clickGps);
		ivGPSButton.setVisibility(View.VISIBLE);

		tvTitle = (TextView) findViewById(R.id.tvPublicTiTle);

		myRadioButton = new MyRadioButton(this, "产品列表", "店面图片");
		myRadioButton.setOnCheckedChanged(this);

		supplierInfoShow = new SupplierInfoShow(this);

		ivReturnButton.setOnClickListener(myClickListener);

		gAdapter = new PurGoodsGridAdapter(this, disCloths, false);
		sAdapter = new PurStoreGridAdapter(this, disStorePicture);
		wShowGoods = new WaterFallGoodsView(this, disCloths);
		wShowStore = new WaterFallShowStore(this, sAdapter, disStorePicture);

		wShowStore.getGridView().setOnItemClickListener(
				myItemPictureClickListener);

		ivBackButton.setOnClickListener(myClickListener);
		ivReturnButton.setOnClickListener(myClickListener);
		ivPhoneButton.setOnClickListener(myClickListener);
		rbCollectButton.setOnClickListener(myClickListener);

		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		String strSupplier = bundle.getString("strSupplier");
		if (strSupplier != null && !strSupplier.equals("")) {
			try {
				supplier = DataUtil.gson.fromJson(strSupplier, Supplier.class);
				tvTitle.setText(supplier.getStoreName());
				supplierInfoShow.show(supplier);
				disStorePicture = supplier.getSupCompanyPicture();
				this.sAdapter.resetList(disStorePicture);
				wShowGoods.setToLoad(ToLoadGoods);
				wShowGoods.loadData();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		checkCollected();

	}

	/**
	 * 检查是否被收藏了
	 */
	private void checkCollected() {
		rbCollectButton.setChecked(false);
		// colSuppliers = CollectSupplierShared.getColSupplierList();
//		if (user != null) {
//			colSuppliers = dataService.getSuppliers(user.getSupId(), 0, 0,
//					MyStateUtil.COLLECTION_SUPPLIER);
//		} else {
			colSuppliers = dataService.getSuppliers(deviceId, 0, 0,
					MyStateUtil.COLLECTION_SUPPLIER);
//		}

		if (colSuppliers != null) {
			for (int i = 0; i < colSuppliers.size(); i++) {
				if (supplier.getSupId() == colSuppliers.get(i).getSupId()) {
					collecteNumber = i;
					rbCollectButton.setChecked(true);
					break;
				}
			}
		}
	}

	@Override
	public void checkOne() {
		// TODO Auto-generated method stub
		isShowGoods = true;
		wShowStore.setListFlag(View.GONE);
		wShowGoods.setListFlag(View.VISIBLE);
	}

	@Override
	public void checkTwo() {
		// TODO Auto-generated method stub
		isShowGoods = false;
		wShowStore.setListFlag(View.VISIBLE);
		wShowGoods.setListFlag(View.GONE);
		sAdapter.notifyDataSetChanged();
	}

	WaterFallGoodsView.ToLoad ToLoadGoods = new WaterFallGoodsView.ToLoad() {
		@Override
		public boolean doLoad() throws Exception {
			// TODO Auto-generated method stub
			if (isShowGoods) {
				GsonBean gsonBean = goodsFromSupplierService.execute(
						wShowGoods.startIndex, wShowGoods.length,
						supplier.getSupId());
				if (CheckStateUtil.check(gsonBean)) {
					List<Cloth> newCloths = DataUtil.gson.fromJson(
							gsonBean.getStrJson(),
							new TypeToken<List<Cloth>>() {
							}.getType());
					if (!wShowGoods.cancleLoad) {
						disCloths.addAll(newCloths);
						wShowGoods.startIndex = disCloths.size();
					}
					return true;
				} else {
					return false;
				}
			}
			return true;
		}

	};

	OnClickListener myClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.ivPublicTitleReturn:
				PurSupplierDetailsActivity.this.finish();
				break;
			case R.id.ivPurDetailsBack:
				PurSupplierDetailsActivity.this.finish();
				break;
			case R.id.ivPurDetailsPhone:
				if (supplier != null) {
					DialShared.saveDialRecord(supplier);
					Intent intent = new Intent(Intent.ACTION_CALL,
							Uri.parse("tel:" + supplier.getSupPhone()));
					startActivity(intent);
				} else {
					ToastUtil.show(getBaseContext(), "供应商电话信息出错!");
				}
				break;
			case R.id.rbPurDetailsCollection:

				if (-1 == collecteNumber) {
					// 收藏
					Log.v("", "收藏");
					rbCollectButton.setChecked(true);
					collecteNumber = colSuppliers.size();
					colSuppliers.add(supplier);
					String time;
					java.text.DateFormat format = new java.text.SimpleDateFormat(
							"yyyy-MM-dd hh:mm:ss");
					time = format.format(new Date());
					dataService.insertSupplier(supplier,
							MyStateUtil.COLLECTION_SUPPLIER);
//					if (user != null) {
//						dataService.insertStat(user.getSupId(),
//								supplier.getSupId(),
//								MyStateUtil.COLLECTION_SUPPLIER, time);
//					} else {
						dataService.insertStat(deviceId, supplier.getSupId(),
								MyStateUtil.COLLECTION_SUPPLIER, time);
//					}

					// CollectSupplierShared.saveColSupplierList(colSuppliers);
					notifyCollect(supplier.getSupId(), false);
				} else {
					// 取消收藏
					colSuppliers.remove(collecteNumber);
					rbCollectButton.setChecked(false);
//					if (user != null) {
//						dataService.deleteCollection(user.getSupId(),
//								supplier.getSupId(),
//								MyStateUtil.COLLECTION_SUPPLIER);
//					} else {
						dataService.deleteCollection(deviceId, supplier.getSupId(),
								MyStateUtil.COLLECTION_SUPPLIER);
//					}

					// CollectSupplierShared.saveColSupplierList(colSuppliers);
					collecteNumber = -1;
					notifyCollect(supplier.getSupId(), true);
				}
				break;

			default:
				break;
			}
		}
	};

	OnItemClickListener onItemGoodsClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			PurCache.cloth = disCloths.get(position);
			final int clothsId = disCloths.get(position).getClothId();
			try {
				ExecutorUtil.getCachedExecutorService().submit(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						clickGoodsService.execute(clothsId);
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
			Intent intent = new Intent(PurSupplierDetailsActivity.this,
					PurGoodsPagerActivity.class);
			MyLoadCloth.sup_id = supplier.getSupId();
			// MyLoadCloth.setExtra(intent, wShowGoods.startIndex,
			// wShowGoods.length, MyLoadCloth.SUP_CLOTH, position,
			// gson.toJson(disCloths));
			MyLoadCloth.setExtra(intent, wShowGoods.startIndex,
					wShowGoods.length, MyLoadCloth.SUP_CLOTH, position,
					disCloths);
			startActivityForResult(intent, 1);
		}
	};

	OnItemClickListener myItemPictureClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			try {
				Intent intent = new Intent(getBaseContext(),
						PubPicturePagerActivity.class);
				SupCache.pictureList = supplier.getSupCompanyPicture();
				PubPicturePagerActivity.ROOT = false;
				startActivity(intent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		checkCollected();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			this.finish();
			return false;
		}
		return false;
	}

	// 通知服务器收藏操作
	private void notifyCollect(final int clothId, final boolean cancle) {
		ExecutorUtil.getCachedExecutorService().submit(new Runnable() {
			@Override
			public void run() {
				try {
					if (EnvironmentUtil.checkNetState(getBaseContext())) {

						if (cancle) {
							cancleCollectSupplierService.execute(clothId);
						} else {
							collectSupplierService.execute(clothId);
						}

					} else {

					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	OnClickListener clickGps = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			try {
				PurMapActivity.LAUNCH_MODE = PurMapActivity.MY_LOC_AND_SUP;
				PurMapActivity.supplier = supplier;
				Intent intent = new Intent(PurSupplierDetailsActivity.this,
						PurMapActivity.class);
				startActivity(intent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	protected void onPause() {
		super.onPause();
		wShowGoods.cancleLoad = true;
	};

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		wShowGoods.cancleLoad = false;
		// wShowGoods.notifyDataChange();
	}
}
